package cn.tedu.sims.service.impl;

import cn.tedu.sims.ex.ServiceException;
import cn.tedu.sims.mapper.NoticeMapper;
import cn.tedu.sims.pojo.dto.NoticeAddNewDTO;
import cn.tedu.sims.pojo.entity.Notice;
import cn.tedu.sims.pojo.vo.NoticeListItemVO;
import cn.tedu.sims.pojo.vo.NoticeStandardVO;
import cn.tedu.sims.service.NoticeService;
import cn.tedu.sims.web.ServiceCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void addNew(NoticeAddNewDTO noticeAddNewDTO) {
        int countByTitle = noticeMapper.countByTitle(noticeAddNewDTO.getTitle());
        if (countByTitle>0){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"发布失败,标题重复");
        }

        Notice notice=new Notice();
        BeanUtils.copyProperties(noticeAddNewDTO,notice);
        notice.setState(1);
        notice.setGmtCreate(LocalDateTime.now());
        int row = noticeMapper.insert(notice);
        if (row!=1){
            throw new ServiceException(ServiceCode.ERR_INSERT,"发布失败,服务器繁忙");
        }
    }

    @Override
    public List<NoticeListItemVO> list() {
        return noticeMapper.list();
    }

    @Override
    public void deleteById(Long id) {
        int countById = noticeMapper.countById(id);
        if (countById!=1){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"删除失败,公告不存在");
        }

        int row = noticeMapper.deleteById(id);
        if (row!=1){
            throw new ServiceException(ServiceCode.ERR_DELETE,"删除失败,服务器繁忙");
        }
    }

    @Override
    public List<NoticeListItemVO> selectByTitle(String title) {
        return noticeMapper.selectByTitle(title);
    }

    @Override
    public NoticeStandardVO selectById(Long id) {
        return noticeMapper.selectById(id);
    }

    @Override
    public void deleteBatch(Long[] list) {
        for (Long id:list){
            int countById = noticeMapper.countById(id);
            if (countById!=1){
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"删除失败,公告不存在");
            }
        }

        int ros=noticeMapper.deleteBatch(list);
        if (ros!=list.length){
            throw new ServiceException(ServiceCode.ERR_DELETE,"删除失败,服务器繁忙");
        }
    }
}
